package com.gitee.filter;

import cn.hutool.core.util.StrUtil;
import com.gitee.client.UserClient;
import com.gitee.enums.ResponseEnum;
import com.gitee.exception.LoginException;
import com.gitee.exception.UserException;
import com.gitee.sdk.UserSDK;
import com.gitee.utils.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class WxAuthFilter extends ZuulFilter {

    @Autowired
    private UserClient userClient;


    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        return request.getRequestURI().startsWith("/canteen-wx");
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        String token = request.getHeader("token");
        // 判断token是否存在
        if (StrUtil.isBlank(token)) {
            throw new LoginException(ResponseEnum.NO_LOGIN);
        }
        // 获取载荷
        Claims claims = JwtUtil.checkJWT(token);
        // 判断token是否过期
        long expireTime = claims.getExpiration().getTime();
        if (new Date().getTime() > expireTime) {
            throw new LoginException(ResponseEnum.NO_LOGIN);
        }
        // 判断用户状态
        Integer userId = (Integer)claims.get("userId");
        if (userId == null) {
            throw new LoginException(ResponseEnum.NO_LOGIN);
        }
        UserSDK user = userClient.getUserSDK(userId);
        if (user == null || !user.getEnabled()) {
            throw new UserException(ResponseEnum.NO_ACCEPT);
        }
        return true;
    }
}
